	package com.mytime.resources;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.CharacterSet;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import com.mytime.database.Category;
import com.mytime.database.PMF;
import com.mytime.util.Functions;

public class AllCategories extends ServerResource {
	
    /**
     * Handles a GET HTTP request.
     * Returns all categories. 
     * @param entity
     */
	@Get
	public Representation getCategories() throws Exception {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		JSONObject categoriesObject = new JSONObject();
		JSONArray categories = new JSONArray();
		
		//Selects categories from database.
		Query query = pm.newQuery(Category.class);
		
		try {
			@SuppressWarnings("unchecked")
			List<Category> categoriesList = (List<Category>) query.execute();
			
			for (Category category: categoriesList) {
				categories.put(category.toJSON());
			}
			categoriesObject.put("categories", categories);
			
		} catch (Exception e) {
			categoriesObject.put("error", e.getMessage());			
			
		} finally {
			query.closeAll();
		}

		return getRepresentation(categoriesObject);
	}

    /**
     * Handles a POST HTTP request.
     * Adds one or more categories. 
     * @param JSONObject containing the information of the categories to be added.
     * @return JSONObject with the result (success or error)
     */
	@Post
	public Representation acceptRepresentation(Representation entity) throws JSONException, IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		JsonRepresentation rep = new JsonRepresentation(entity);
		JSONObject result = new JSONObject();
		
        try {
        	//Getting data
			JSONObject jsonobj = rep.getJsonObject();
			
			//Getting categories to be added
			JSONArray categories = jsonobj.getJSONArray("categories");
			int categoriesAdded = 0;
			
			for (int i = 0; i < categories.length(); i++) {
				//Category information
				JSONObject categoryObj = categories.getJSONObject(i);
				
				//Getting key
				String categoryId = categoryObj.getString("id");
				
				//Preparing query to check if the event already exists
				String filter = "id == \'" + categoryId + "\'";
				Query query = pm.newQuery(Category.class);
				query.setFilter(filter);
	
				//Executing query	
				@SuppressWarnings("unchecked")
				List<Category> results = (List<Category>) query.execute();
				
				if (results.size() == 0) {
					Category category = new Category();
					category.setId(Functions.removeSpecialCharacters(categoryObj.getString("name")).
							toLowerCase().replaceAll(" ", "_"));
					category.setName(categoryObj.getString("name"));
					categoriesAdded += 1;
					
	    			try {
	    				pm.makePersistent(category);
	    				
	    			} catch(Exception e) {
	    				result.put("error", e.getMessage());
	    			} 
	
				} else {
					//Category already exists.
					result.put("error", "This category already exists.");
				}
        	}
			
			result.put("Added", categoriesAdded);
			
        } catch (JSONException e) {
			e.printStackTrace();
			result.put("error", e.getMessage());
			
		} finally {
    		pm.close(); 		
    	}
        
        return getRepresentation(result);

	}
	
	/**
	 * Returns the JSON representation for a given JSON object.
	 * */
    private Representation getRepresentation(JSONObject jsonObject) {
    	JsonRepresentation jr = new JsonRepresentation(jsonObject);
    	jr.setCharacterSet(CharacterSet.UTF_8);
    	
    	return jr;
    }    

}
